<template>
  <van-action-sheet
    v-model:show="bindPhoneNumberShow"
    :cancel-text="props.cancelText"
    :close-on-click-overlay="false"
    :closeable="props.closeable"
    :style="{ height: parseCssValue(props.height, 'vh'), maxHeight: parseCssValue(props.height, 'vh') }"
    :title="props.title"
    teleport="body"
    @cancel="bindPhoneNumberShow = false"
  >
    <van-form @submit="emit('submit', loginPhone, smsCaptcha)">
      <slot name="head"></slot>
      <van-field
        v-model="loginPhone"
        :error-message="phoneNumberRight ? '' : '手机号格式不正确'"
        :style="{ lineHeight: parseCssValue(props.lineHeight, 'vw') }"
        clearable
        maxlength="11"
        placeholder="请输入手机号"
        required
      />
      <van-field
        v-model="imgCaptcha"
        :style="{ lineHeight: parseCssValue(props.lineHeight, 'vw') }"
        center
        clearable
        maxlength="4"
        placeholder="请输入图形验证码"
        required
      >
        <template #button>
          <img
            :src="captchaUrl"
            alt="captcha"
            class="verificationImage"
            @click.prevent="updateCaptchaUrl(captchaType)"
          />
        </template>
      </van-field>
      <van-field
        v-model="smsCaptcha"
        :style="{ lineHeight: parseCssValue(props.lineHeight, 'vw') }"
        center
        clearable
        maxlength="6"
        placeholder="请输入短信验证码"
      >
        <template #button>
          <van-button
            v-if="!countDown"
            :disabled="captchaDisable"
            class="verificationImage"
            size="small"
            type="primary"
            @click="sendSmsCode"
          >
            发送
          </van-button>
          <van-button v-else class="verificationImage" size="small" type="primary">
            {{ '已发送 ' + countDown }}
          </van-button>
        </template>
      </van-field>
      <slot name="foot"></slot>
      <van-button
        :disabled="!bindValidate"
        block
        native-type="submit"
        size="normal"
        style="margin-top: 1rem"
        type="primary"
      >
        {{ props.submitText }}
      </van-button>
    </van-form>
  </van-action-sheet>
</template>

<script lang="ts" setup>
import { Ref } from 'vue'
import { baseURL } from '@/framework/requests'
import { localStorageMethods } from '@/framework/common/storage'
import { parseCssValue } from '@/framework/utils/common'
import { AUTHORIZATION_TOKEN } from '@/framework/constant'
import { sendSms } from '@/framework/apis/sms'
import { ResponseDataType } from '@/framework/types/api'
import { showSuccess } from '@/framework/common/notify'

const props = withDefaults(
  defineProps<{
    modelValue: any
    title?: string
    captchaType: string
    submitText?: string
    height?: number | string
    lineHeight?: number | string
    cancelText?: string
    closeable?: boolean
  }>(),
  {
    title: '',
    submitText: '确定',
    height: 70,
    lineHeight: 10,
    cancelText: undefined,
    closeable: false
  }
)
const emit = defineEmits<{
  (e: 'update:modelValue', value: any): void
  (e: 'submit', phoneNumber: any, smsCode: any): void
}>()
const { modelValue, captchaType } = toRefs(props)
const bindPhoneNumberShow = ref(modelValue.value)
watch(
  () => bindPhoneNumberShow.value,
  () => emit('update:modelValue', bindPhoneNumberShow.value)
)
watch(
  () => modelValue.value,
  () => (bindPhoneNumberShow.value = modelValue.value)
)
const loginPhone = ref('')
const phoneNumberRight = computed(() => {
  // 1.1 当输入的手机号大于10位进行验证
  if (loginPhone.value.length > 10) {
    return /[1][3,4,5,6,7,8,9][0-9]{9}$/.test(loginPhone.value)
  } else {
    return true
  }
})
const imgCaptcha = ref('')
const captchaUrl: Ref<string> = ref('')
const getCaptchaUrl = (captchaType: string) =>
  baseURL +
  '/captcha.jpg?token=' +
  localStorageMethods.getLocalStorage(AUTHORIZATION_TOKEN) +
  '&captchaType=' +
  captchaType
const updateCaptchaUrl = (captchaType: string) =>
  (captchaUrl.value = getCaptchaUrl(captchaType + '_CAPTCHA') + '&r=' + Math.random())
const smsCaptcha = ref('')
const countDown = ref(0)
const captchaDisable = computed(() => {
  if (
    loginPhone.value.length > 10 &&
    phoneNumberRight.value &&
    imgCaptcha.value &&
    imgCaptcha.value.length === 4
  ) {
    return false
  } else {
    return true
  }
})
let timeIntervalID: any
const sendSmsCode = () => {
  sendSms(loginPhone.value, captchaType.value, imgCaptcha.value)
    .then((resp: ResponseDataType) => {
      countDown.value = resp.payload.internal
      timeIntervalID = setInterval(() => {
        countDown.value--
        if (countDown.value == 0) {
          clearInterval(timeIntervalID)
        }
      }, 1000)
      showSuccess('短信已发送')
    })
    .catch(() => {
      reset()
    })
}
const reset = () => {
  smsCaptcha.value = ''
  imgCaptcha.value = ''
  updateCaptchaUrl(captchaType.value)
}
const bindValidate = computed(() => {
  return (
    phoneNumberRight.value &&
    imgCaptcha.value &&
    imgCaptcha.value.length === 4 &&
    smsCaptcha.value &&
    smsCaptcha.value.length >= 4
  )
})
onMounted(() => {
  reset()
})
</script>

<style lang="less" scoped>
.verificationImage {
  text-align: center; /* 水平居中文字 */
  justify-content: center; /* Flexbox方式让文字在按钮内垂直居中 */
  display: flex; /* 开启flex布局 */
  align-items: center; /* 垂直居中flex项 */
  height: 10vw;
  width: 16vw;
}
</style>
